package com.example.helper2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONObject;

public class fragment_time_line extends Fragment {

    private View root;
    private ListView lvTimeLine;
    private List<TimeLine> timeLineList;
    private TimeLineAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        root = inflater.inflate(R.layout.time_line,container,false);
        lvTimeLine = (ListView) root.findViewById(R.id.lvTimeLine);
        timeLineList = new ArrayList<>(20);
        initData();
        updateTimeline();
        Toast.makeText(getActivity(),"已从服务器取得信息",Toast.LENGTH_SHORT).show();
        return root;
    }


    private void initData() {
        // 初始数据
        timeLineList.add(new TimeLine("03月23日  17:14", "27省区市下调应急响应级别，京津冀鄂仍为一级"));
        timeLineList.add(new TimeLine("03月23日  16:22", "一留美学生发病前外出就餐逛街未戴口罩，抵京后确诊"));
        timeLineList.add(new TimeLine("03月23日  15:57", "国家移民局：外国人不如实填报信息不准入境"));
        timeLineList.add(new TimeLine("03月23日  15:47", "林郑月娥：25日起所有非香港居民乘飞机抵港不准入境"));
        timeLineList.add(new TimeLine("03月23日  15:34", "海关总署：所有出入境人员必须健康申报，隐瞒或虚报将追究法律责任"));
        timeLineList.add(new TimeLine("03月23日  15:28", "民航局回应调整北京航班入境点"));
        timeLineList.add(new TimeLine("03月23日  15:19", "国家卫健委：湖北和武汉仍存在出现散发甚至聚集性病例可能"));
        timeLineList.add(new TimeLine("03月23日  13:01", "北京今天上午报告境外输入确诊病例15例"));
        timeLineList.add(new TimeLine("03月23日  11:37", "我驻美大使崔天凯回应“病毒来自美国军方实验室”说法"));
        adapter = new TimeLineAdapter(getActivity(), timeLineList);
        lvTimeLine.setAdapter(adapter);
        // 在线获取数据
    }

    private Handler tlhandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String time = data.getString("time");
            String title = data.getString("title");
            timeLineList.add(new TimeLine(time,title));

            Collections.sort(timeLineList, new Comparator<TimeLine>() {
                @Override
                public int compare(TimeLine o1, TimeLine o2) {
                    return o2.getTime().compareTo(o1.getTime());
                }
            });

            // 用数据去填充适配器
            adapter = new TimeLineAdapter(getActivity(), timeLineList);
            lvTimeLine.setAdapter(adapter);

            //
            // TODO: 更新界面
            //
//            Log.i("mylog","请求结果-->" + val);
        }
    };

    private void updateTimeline() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url_s = "http://wolfdnd.top:2020/timeline";
                    URL url = new URL(url_s);
                    HttpURLConnection myconnect = (HttpURLConnection)url.openConnection();
                    // 设置请求方式
                    myconnect.setRequestMethod("GET");
                    myconnect.setConnectTimeout(5000);
                    myconnect.connect();

                    // 获取数据
                    if(myconnect.getResponseCode() == 200){
                        InputStream inputStream = myconnect.getInputStream();
                        InputStreamReader input = new InputStreamReader(inputStream);
                        BufferedReader buffer = new BufferedReader(input);
                        String inputLine;
                        StringBuffer resultData  = new StringBuffer();//StringBuffer字符串拼接很快
                        while((inputLine = buffer.readLine())!= null){
                            resultData.append(inputLine);
                        }
                        String text = resultData.toString();
                        parseJson(text);
//                        Log.v("out---------------->",text);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            private void parseJson(String text){
                try {
                    JSONArray jsonArray = new JSONArray(text);
                    int length = jsonArray.length();
                    String test;
                    for(int i=0; i < length; i++){
                        JSONObject userMsg = jsonArray.getJSONObject(i);
                        Log.v("查看记录",userMsg.toString());
                        String time = userMsg.getString("time");
                        String title = userMsg.getString("title");

                        Message msg = new Message();
                        Bundle data = new Bundle();
                        data.putString("time",time);
                        data.putString("title",title);
                        msg.setData(data);
                        tlhandler.sendMessage(msg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
